package model

import (
	"vueBasic/app/admin/filter"
	"vueBasic/extend/conv"
	"vueBasic/global"
)

var AdminLogM = new(adminLog)

/**
 * @description(日志管理模型)
 * @buildcode(true)
 */
type adminLog struct {
	Id              int    `json:"id"`               //编号
	ApplicationName string `json:"application_name"` //所属应用
	Type            int    `json:"type"`             //日志类型 登录日志-1;操作日志-2;异常日志-3
	Username        string `json:"username"`         //用户名
	Url             string `json:"url"`              //请求url
	Ip              string `json:"ip"`               //客户端ip
	Useragent       string `json:"useragent"`        //浏览器信息
	Content         string `json:"content"`          //请求内容
	Errmsg          string `json:"errmsg"`           //异常信息
	CreateTime      int64  `json:"create_time"`      //创建时间
}

/**
 * @description(日志管理数据表)
 * @buildcode(true)
 */
func (*adminLog) TableName() string {
	return global.CONF.Database.Db.Prefix + "log"
}

// 获取列表
func (*adminLog) GetList(req *filter.AdminLogListReq) ([]*filter.AdminLogListRes, int64, error) {
	var (
		list  []*filter.AdminLogListRes
		count int64
	)
	query := global.DB.Model(&adminLog{})
	if !conv.IsEmpty(req.Username) {
		query = query.Where("username=?", req.Username)
	}
	if !conv.IsEmpty(req.Type) {
		query = query.Where("type=?", req.Type)
	}
	if !conv.IsEmpty(req.CreateTime) {
		query = query.Where("create_time BETWEEN ? AND ?", conv.UnixTime(req.CreateTime[0]), conv.UnixTime(req.CreateTime[1]))
	}
	if err := query.Limit(req.Limit).Offset((req.Page - 1) * req.Limit).Find(&list).Error; err != nil {
		return nil, 0, err
	}
	query.Count(&count)
	return list, count, nil
}

// 添加
func (*adminLog) Add(req filter.AdminLogAddReq) error {
	entity := adminLog{}
	entity.ApplicationName = req.ApplicationName
	entity.Type = req.Type
	entity.Username = req.Username
	entity.Url = req.Url
	entity.Ip = req.Ip
	entity.Useragent = req.Useragent
	entity.Content = req.Content
	entity.Errmsg = req.Errmsg
	entity.CreateTime = req.CreateTime
	if err := global.DB.Create(&entity).Error; err != nil {
		return err
	}
	return nil
}

// 删除
func (*adminLog) Delete(ids []string) (uint, error) {
	query := global.DB.Where("id IN ?", ids)
	err := query.Delete(&adminLog{}).Error
	if err != nil {
		return 0, err
	}
	return 1, nil
}

// 详情
func (*adminLog) GetLogInfoById(req *filter.AdminLogInfoReq) (*adminLog, error) {
	entity := adminLog{}
	if err := global.DB.Where("id=?", req.Id).Limit(1).First(&entity).Error; err != nil {
		return nil, err
	}
	return &entity, nil
}
